import React, { useEffect, useState } from "react";
import styles from "./index.module.scss";
import {
  Form,
  Input,
  Button,
  Dialog,
  Switch,
  Toast,
  Skeleton,
  Modal
} from "antd-mobile";
import dayjs from "dayjs";
import type { DatePickerRef } from "antd-mobile/es/components/date-picker";

// 路由
import { redirect, useNavigate } from "react-router-dom";

// 导入仓库
import {
  myUserToken,
  storeUser,
  changeIsLogin,
  changeUser,
} from "@/store/userSlice";

// 导入带有类型的属性，方法 1.
import { useAppDispatch, useAppSelector } from "../../hooks";

// 请求
import {
  ApiCheckLogin,
  ApiMemberCarAdd,
  ApiMemberCarList,
  ApiMemberCarUpdate,
  ApiMemberCarUpdateStatus,
  ApiMemberInfo,
  ApiMemberUpdate,
} from "@/utils/api";

// 验证码

// 加密解密
// import crypt from "@/utils/crypto";

// import { lorem } from "./demos-util";
// 导入车牌号组件
// import { createRoot } from "react-dom/client";
import LicenseKeyboard from "./keyboard/index";
import "./keyboard/style.scss";

// 图标
import { AddCircleOutline } from "antd-mobile-icons";
// 定义item接口
// interface RootObject {
//   name: string;
//   sex: number;
//   birthday: any;
//   captcha: number | string;
//   mobile: string | number;
//   plate_number: string;
//   member: Array<string>;
// }
// 车牌号
interface memberData<T> {
  code: number;
  msg: string;
  data: T;
}
// 车牌号
interface Datum {
  id?: number;
  member_id?: number;
  status?: number;
  code?: string;
  plate_number?: string;
  sort?: number;
  created_at?: string;
  updated_at?: string;
  isEdit?: boolean;
}

export default () => {
  // 表单更新
  const [form] = Form.useForm();
  // 导入仓库 2.使用属性
  const userToken = useAppSelector(myUserToken);
  // const user = useAppSelector(storeUser);

  // 导入仓库 2.使用方法
  // const dispatch = useAppDispatch();

  // 路由跳转
  const navigate = useNavigate();
  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // 请求登录状态
  const checkLogin = async () => {
    console.log(userToken.openid, "openid");
    const res = await ApiCheckLogin(userToken.openid);
    if (res.code == 0) {
      // 当前页面使用
      setMember_id(res.data.member_id);
      return res.data.member_id;
    } else {
      console.log("未登录");
      return;
    }
  };
  // 车牌号
  const [showKeyboard, setShowKeyboard] = useState(false);
  // 显示输入框
  // const [showInput, setShowInput] = useState(false);
  // 输入车牌号
  const [myIndex, setIndex] = useState(0);
  // 输入车牌号
  const [memberVal, setMemberVal] = useState("");
  // 会员车辆
  const [member, setMember] = useState<Datum[]>([]);
  // 骨架屏
  const [loading, setLoading] = useState(true);

  // 添加或修改车辆 保存ApiMemberCarAdd
  const saveMemberCarList = async (index) => {
    // 修改
    const item = member[index];
    if (item?.id) {
      console.log(item, "item");
      // 修改接口
      await ApiMemberCarUpdate({
        member_car_id: item.id,
        plate_number: item.plate_number!,
      });
      // 修改成功
      Toast.show({ content: "保存成功", icon: "success" });
      mapMemberCarList();
    } else {
      // 添加
      console.log(memberVal, "memberVal");
      // 请求添加
      await ApiMemberCarAdd(memberVal);
      // 成功
      Toast.show({ content: "添加成功", icon: "success" });
      // 车辆详情
      await mapMemberCarList();
      // 滚动到顶部
      scrollToTop();
    }
  };

  // 删除车辆deleteMemberCar 或取消添加
  const deleteMemberCar = async (index) => {
    // 修改
    const item = member[index];
    if (item?.id) {
      console.log(item, "item");
      // 成功
      // 询问是否删除
      const result = await Modal.confirm({
        content: "是否启用车牌号" + member[index].plate_number,
      });
      // 确认修改
      if (result) {
        await ApiMemberCarUpdate({
          member_car_id: item.id,
          plate_number: item.plate_number!,
        });
        // 提示
        Toast.show({
          content: "删除" + item.plate_number + "成功",
          icon: "success",
        });
        await mapMemberCarList();
      } else {
        Toast.show({ content: "已取消删除", icon: "success" });
      }
    } else {
      Toast.show({ content: "已取消添加", icon: "success" });
    }
  };

  // 修改编辑状态
  const editMemberCarList = async (index) => {
    console.log(member[index], "index");
    // 修改 变 保存
    // 创建一个新的数组，修改 isEdit 属性
    const updatedMember = member.map((m, i) =>
      i === index ? { ...m, isEdit: false } : m
    );
    // 更新状态
    setMember(updatedMember);
  };

  // 输入车牌号 或修改车牌号
  const changeMember = async (index, val) => {
    // 判断是否有id
    const item = member[index];
    // console.log(item);
    if (item?.id) {
      // 修改
      // 创建新的 member 数组，更新指定索引的 plate_number
      const newMember = [...member];
      newMember[index] = { ...newMember[index], plate_number: val };
      // 更新 member 状态
      setMember(newMember);
      // console.log(item.plate_number);
    } else {
      // 添加
      console.log(index,val);
      // setMemberVal(val);
      const newMember = [...member];
      newMember[index] = { ...newMember[index], plate_number: val };
      // 更新 member 状态
      setMember(newMember);
      console.log(memberVal, "memberVal");
    }
  };

  // 修改车辆状态
  const changeStatus = async (index, checked) => {
    const item = member[index];
    // 修改
    if (item?.id) {
      // 确认提醒
      const result = await Modal.confirm({
        content: "是否启用车牌号" + item.plate_number,
      });
      // 确认修改
      if (result) {
        const res = await ApiMemberCarUpdateStatus({
          member_car_id: item.id,
          status: checked ? 1 : 0,
        });
        if (res.code == 0) {
          Toast.show({
            content: "保存成功,启用" + member[index].plate_number,
            icon: "success",
          });
          // 二次处理
          await mapMemberCarList();
          // 初始化
          form.setFieldsValue({
            contacts: [],
          });
          // window.scrollTo(0, 0);
          // 丝滑点
          scrollToTop();
        }
      } else {
        console.log(member[index].status);
        const status = member[index].status;
        const data = member.map((item) => {
          return {
            ...item,
            status,
          };
        });
        setMember(data);
        // 重新初始化
        form.setFieldsValue({
          contacts: [],
        });
        Toast.show({ content: "已取消修改" });
      }
    }
  };

  // 跳转主页
  const determine = async () => {
    // 返回主页
    navigate("/index");
  };

  // 回到顶部
  const handleScroll = () => {
    // 检查滚动位置，当滚动位置大于某个值时显示回到顶部按钮
    const scrollTop = window.scrollY;
    const threshold = 200;
    // setIsVisible(scrollTop > threshold);
  };
  // 回到顶部
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: "smooth", // 使用平滑滚动效果
    });
  };
  // 回到顶部 添加滚动监听
  React.useEffect(() => {
    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  // 车辆详情 二次处理数据
  const mapMemberCarList = async () => {
    const res = await ApiMemberCarList();
    // 二次处理
    const data = res.data.map((item) => {
      return {
        ...item,
        isEdit: true,
      };
    });
    console.log(data);
    setMember(data);
  };

  // 车辆详情
  const getMemberCarList = async () => {
    // 请求车辆列表
    try {
      // 二次处理
      await mapMemberCarList();
    } finally {
      // 无论请求成功或失败，都设置 loading 为 false
      // 使用骨架屏
      setLoading(false);
    }
  };

  // 检查登录 获取member_id
  const initData = async () => {
    // 请求用户信息
    // getAccessToken();
    const member_id = await checkLogin();
    if (!member_id) return;
    // 用于后续 获取会员详情信息
    // await getMemberInfo(member_id);
    // 请求车辆列表
    getMemberCarList();
  };

  // 挂载页面
  useEffect(() => {
    // 检查登录 获取member_id
    initData();
  }, []);

  // 设置默认值+监听
  useEffect(() => {
    // 更新表单
    form.setFieldsValue({
      contacts: member,
    });
  }, [member]);

  return (
    <div className={styles.form}>
      {/* <Skeleton.Title animated /> */}
      <Skeleton.Paragraph
        animated
        lineCount={15}
        style={{ display: loading ? "block" : "none" }}
      />
      <Form
        style={{ display: loading ? "none" : "block" }}
        layout="horizontal"
        form={form}
        footer={
          <Button
            block
            type="submit"
            color="primary"
            size="large"
            // shape="rounded"
            onClick={determine}
          >
            返回主页
          </Button>
        }
      >
        <Form.Header>会员信息</Form.Header>
        <Form.Array
          name="contacts"
          onAdd={(operation) => {
            operation.add({ plate_number: "粤" });
            setMember([...member, { plate_number: "粤" }]);
            // setMemberVal({ ...memberVal, isEdit: true });
            return;
          }}
          renderAdd={() => (
            <span>
              <AddCircleOutline /> 添加
            </span>
          )}
          renderHeader={({ index }, { remove }) => (
            <>
              <span>车牌号{index + 1}</span>
              <a
                onClick={() => saveMemberCarList(index)}
                style={{
                  float: "right",
                  marginLeft: "6px",
                  display: member[index]?.isEdit ? "none" : "inline-block",
                }}
              >
                保存
              </a>
              <a
                onClick={() => editMemberCarList(index)}
                style={{
                  float: "right",
                  marginLeft: "6px",
                  display: member[index]?.isEdit ? "inline-block" : "none",
                }}
              >
                修改
              </a>
              <a
                onClick={() => {
                  // 确认删除吗？
                  deleteMemberCar(index);
                  remove(index);
                }}
                style={{ float: "right" }}
              >
                删除
              </a>
            </>
          )}
        >
          {(fields) =>
            fields.map(({ index }) => (
              <>
                {/* <Form.Item
                  name={[index, "plate_number"]}
                  label="车牌号"
                  // rules={[{ required: true, message: "姓名不能为空" }]}
                >
                  <Input
                    placeholder="请输入车牌号"
                    onChange={(val) => changeMember(index, val)}
                    disabled={member[index]?.isEdit}
                  />
                </Form.Item> */}
                <Form.Item
                  name={[index, "plate_number"]}
                  label="车牌号"
                  // rules={[{ required: true, message: "姓名不能为空" }]}
                >
                  <Input
                    placeholder="请输入车牌号"
                    onChange={(val) => changeMember(index, val)}
                    disabled={member[index]?.isEdit}
                    onClick={() => {
                      // 设置索引
                      setIndex(index);
                      console.log(myIndex);
                      setShowKeyboard(!showKeyboard);
                    }}
                  />
                </Form.Item>
                <LicenseKeyboard
                  visible={showKeyboard}
                  done={() => setShowKeyboard(false)}
                  onChange={(value: any) => changeMember(myIndex, value)}
                  // onChange={(value) => handleNameInputChange("member", value)}
                  value={member[index]?.plate_number as string}
                />
                <Form.Item
                  name={[index, "created_at"]}
                  label="创建时间"
                  style={{
                    display: member[index]?.id ? "inline-block" : "none",
                  }}
                >
                  <Input
                    placeholder={dayjs(Date.now()).format(
                      "YYYY-MM-DD HH:mm:ss"
                    )}
                    disabled
                  />
                </Form.Item>
                <Form.Item
                  name={[index, "updated_at"]}
                  label="更新时间"
                  style={{
                    display: member[index]?.id ? "inline-block" : "none",
                  }}
                >
                  <Input
                    placeholder={dayjs(Date.now()).format(
                      "YYYY-MM-DD HH:mm:ss"
                    )}
                    disabled
                  />
                </Form.Item>
                <Form.Item
                  name={[index, "status"]}
                  label="启用状态"
                  style={{
                    display: member[index]?.id ? "inline-block" : "none",
                  }}
                >
                  <Switch
                    defaultChecked={index == 0 ? true : false}
                    onChange={(checked) => changeStatus(index, checked)}
                    disabled={member[index]?.isEdit}
                  />
                </Form.Item>
              </>
            ))
          }
        </Form.Array>
      </Form>
    </div>
  );
};

  // 初始化检验是否注册
  // const getAccessToken = async () => {
  //   // 是否已注册
  //   // const isRegister = checkRegister();
  //   // 是否有accessToken
  //   const encryptedUserToken = checkUserToken();
  //   if (encryptedUserToken) {
  //     // 有
  //     // 判断是否过期？
  //     console.log("已注册过");
  //   } else {
  //     console.log("未注册过");
  //     pushRegister();
  //   }
  // };

  // 去到注册页;
  // const pushRegister = () => {
  //   // window.location.href = "http://127.0.0.1:8080";
  //   navigate("/register");
  // };

  // 解密accessToken 检测是否有token,并检查过期
  // const checkUserToken = () => {
  //   // 检查是否存在已加密的用户令牌信息在 localStorage 中
  //   const encryptedUserToken = localStorage.getItem("encryptedUserToken");

  //   if (encryptedUserToken) {
  //     // 用户已登录，解密用户令牌并执行相应逻辑
  //     const decryptedUserToken = crypt.decrypt(encryptedUserToken);
  //     // console.log("解密的 user_token:", decryptedUserToken);
  //     // 执行其他逻辑，如设置用户状态、重定向等
  //     // 是否过期，过期重新请求，否则跳转
  //     // window.location.href = 'http://mfmaef89.beesnat.com/index';
  //     return decryptedUserToken;
  //   }
  //   return false;
  // };
  
  // 表单提交事件
  // const onFinish = (values: any) => {
  //   console.log("values", values);
  //   Dialog.alert({
  //     content: <pre>{JSON.stringify(values, null, 2)}</pre>,
  //   });
  // };